package com.sikaryofficial.backend.manager.information;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sikaryofficial.backend.constant.MyStatisticsTypeEnum;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleEvaluateReplyListReq;
import com.sikaryofficial.backend.domain.dto.req.information.ArticleEvaluateReplyReq;
import com.sikaryofficial.backend.domain.dto.resp.information.ArticleEvaluateReplyDTO;
import com.sikaryofficial.backend.service.IArticleEvaluateReplyService;
import com.sikaryofficial.backend.service.IAttachmentService;
import com.sikaryofficial.backend.service.IPointsDetailStrategy;
import com.sikaryofficial.backend.service.statistics.MyStatisticsProcessor;
import com.sikaryofficial.backend.service.statistics.MyStatisticsEvent;
import com.sikaryofficial.backend.service.user.UserCacheService;
import com.sikaryofficial.common.core.constant.PointRuleConstant;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import com.sikaryofficial.system.api.model.att.AttachmentResp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author : qinjinyuan
 * @desc :  文章数据同步管理类
 * @date : 2024/03/13 11:50
 */
@Component
@Slf4j
public class ArticleEvaluateReplyManager {
    @Autowired
    private IArticleEvaluateReplyService replyService;
    @Autowired
    private UserCacheService userCacheService;
    @Autowired
    private MyStatisticsProcessor myListener;
    @Autowired
    private IAttachmentService attachmentService;
    @Resource
    private Map<String, IPointsDetailStrategy> pointsDetailStrategyMap;
    /**
     * 保存文章评价
     *
     * @param req
     * @return
     */
    public ArticleEvaluateReplyDTO save(ArticleEvaluateReplyReq req) {
        Long userId = SecurityUtils.getUserId();
        ArticleEvaluateReplyDTO evaluateReplyDTO = replyService.saveReply(req);
        IPointsDetailStrategy pointsDetailStrategy = pointsDetailStrategyMap.get(PointRuleConstant.ARTICLE_EVALUATE_REPLY + IPointsDetailStrategy.SUFFIX);
        if (Objects.nonNull(evaluateReplyDTO)) {
            // 填充头像数据
            evaluateReplyDTO.setAvatar(userCacheService.getSignUserAvatar(evaluateReplyDTO.getCreatedBy()));
            // 填充昵称
            evaluateReplyDTO.setNickName(userCacheService.getSignUserNickName(evaluateReplyDTO.getCreatedBy()));
            // 保存附件信息
            attachmentService.saveAttachmentList(evaluateReplyDTO.getArticleEvaluateReplyId(), req.getAttachmentList(), SecurityUtils.getUserId());
            // 文章回复积分获取
            pointsDetailStrategy.updatePoints(evaluateReplyDTO.getArticleEvaluateReplyId(), userId);
        }
        // 3.1 添加文章评价统计
        myListener.addMyStatistics(new MyStatisticsEvent(MyStatisticsTypeEnum.COMMENTS_ARTICLE_REPLAY.getBusinessType(), userId, req.getArticleEvaluateId()));
        // 3.2 添加该文章评论对应的评论统计
        myListener.addMyStatistics(new MyStatisticsEvent(MyStatisticsTypeEnum.COMMENTS_ARTICLE_REPLAY_COUNT.getBusinessType(), userId, req.getArticleEvaluateId()));
        return evaluateReplyDTO;
    }

    public IPage<ArticleEvaluateReplyDTO> listPage(ArticleEvaluateReplyListReq req) {
        if (Objects.nonNull(req.getArticleEvaluateId()) && req.getArticleEvaluateId() <= 0) {
            return new Page<>(req.getPageNum(), req.getPageSize(), 0);
        }
        if (Objects.isNull(req.getUserId()) || req.getUserId() <= 0) {
            req.setUserId(SecurityUtils.getUserId());
        }
        Page<ArticleEvaluateReplyDTO> customerPage = new Page<>(req.getPageNum(), req.getPageSize());
        IPage<ArticleEvaluateReplyDTO> evaluateDTOIPage = replyService.replyList(customerPage, req);
        List<ArticleEvaluateReplyDTO> replyRecords = evaluateDTOIPage.getRecords();
        if (CollUtil.isEmpty(replyRecords)) {
            return new Page<>(req.getPageNum(), req.getPageSize(), 0);
        }
        // 1、填充头像数据
        Map<Long, String> userAvatarMap = userCacheService.getMultiUserAvatar(replyRecords.stream().map(ArticleEvaluateReplyDTO::getCreatedBy).collect(Collectors.toList()));
        // 填充昵称
        Map<Long, String> userNickNameMap = userCacheService.getMultiUserNickName(replyRecords.stream().map(ArticleEvaluateReplyDTO::getCreatedBy).collect(Collectors.toList()));
        replyRecords.forEach(item -> {
            item.setAvatar(MapUtils.getString(userAvatarMap, item.getCreatedBy(), ""));
            item.setNickName(MapUtils.getString(userNickNameMap, item.getCreatedBy(), ""));
        });
        // 2、填充用户行为数据
        replyService.buildUserActionData(replyRecords);
        // 3、填充附件
        List<Long> replyIds = replyRecords.stream().map(ArticleEvaluateReplyDTO::getArticleEvaluateReplyId).collect(Collectors.toList());
        Map<Long, List<AttachmentResp>> attachmentMap = attachmentService.getAttachmentByIds(replyIds);
        replyRecords.forEach(item -> item.setAttachmentList(attachmentMap.get(item.getArticleEvaluateReplyId())));
        return evaluateDTOIPage;
    }
}
